package com.andnnl.menu;

import com.alibaba.fastjson.JSON;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created by chenss on 2021/3/16.
 */
public class MenuTest {
    public static void main(String[] args) {

        List<String> s = Stream.of("one", "two", "three", "four")
                .filter(e -> e.length() > 3)
                .peek(e -> System.out.println("Filtered value: " + e))
                .map(String::toUpperCase)
                .peek(e -> System.out.println("Mapped value: " + e))
                .collect(Collectors.toList());
        System.out.println(s);
        MenuTest menuTest = new MenuTest();
//        menuTest.testtree();
        menuTest.testtree2();
    }

    public void testtree() {
        //模拟从数据库查询出来
        List<Menu> menus = getMenus();

        //获取父节点
        List<Menu> collect = menus.stream().filter(m -> m.getParentId() == 0).map(
                (m) -> {
                    m.setChildList(getChildrens(m, menus));
                    return m;
                }
        ).collect(Collectors.toList());
        System.out.println("-------转json输出结果-------");
        System.out.println(JSON.toJSON(collect));
    }
    public void printTree(List<Menu> list,String lever){
        if(list==null || list.size()==0)return;
        for (Menu menu : list) {
            System.out.println(lever+menu.getName());
            printTree(menu.getChildList(),lever+"    ");
        }
    }

    public void testtree2() {
        //模拟从数据库查询出来
        List<Menu> menus = getMenus();

        List<Menu> collect = menus.stream()
                .filter(m -> m.getParentId() == 0)
                .peek(m -> m.setChildList(getChildrens(m, menus)))
                .collect(Collectors.toList());
        System.out.println("-------转json输出结果-------");
        System.out.println(JSON.toJSON(collect));
        printTree(collect,"");
    }


    private List<Menu> getMenus() {
        return Arrays.asList(
                new Menu(1, "根节点", 0),
                new Menu(2, "子节点1", 1),
                new Menu(3, "子节点1.1", 2),
                new Menu(4, "子节点1.2", 2),
                new Menu(5, "根节点1.3", 2),
                new Menu(6, "根节点2", 1),
                new Menu(7, "根节点2.1", 6),
                new Menu(8, "根节点2.2", 6),
                new Menu(9, "根节点2.2.1", 7),
                new Menu(10, "根节点2.2.2", 7),
                new Menu(11, "根节点3", 1),
                new Menu(12, "根节点3.1", 11)
        );
    }

    /**
     * 递归查询子节点
     *
     * @param root 根节点
     * @param all  所有节点
     * @return 根节点信息
     */
    private List<Menu> getChildrens(Menu root, List<Menu> all) {
        List<Menu> children = all.stream().filter(
                m -> m.getParentId() == root.getId()
        ).peek(m ->
                m.setChildList(getChildrens(m, all))
        ).collect(Collectors.toList());
        return children;
    }
}
